package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    public R<String> remove(Long id) {

        //检查dish是否跟当前分类有关联
        //创建条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);

        //调用查询方法
        //根据返回值进行判断
        if (dishService.count(dishLambdaQueryWrapper)>0){
            //抛出业务异常
            throw new CustomException("当前分类下存在菜品，不能删除");
        }

        //检查setmeal是否跟当前分类有关联
        //创建条件构造器
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);

        //调用查询方法
        //根据返回值进行判断
        if (setmealService.count(setmealLambdaQueryWrapper)>0){
            //抛出业务异常
            throw new CustomException("当前分类下存在套餐，不能删除");
        }

        //调用删除方法，进行删除，返回信息
        super.removeById(id);
        return R.success("删除成功");
    }
}
